#!/bin/bash
#target: install mariadb
#version: v1.1 add character-set-server=utf8mb4
set -u -e
tar_local="/root/mariadb-10.11.7-linux-systemd-x86_64.tar.gz"
install_path="/usr/local/"
data_path="/data/mysql/"
tar_name="${tar_local##*/}"
tar_dir_name="${tar_name%.tar.gz}"


# judge user if root

if [ $UID -ne 0 ];then
	echo -e "you need root to run this script! \E[1;32mexit.\E[0m"
	exit
fi

# first,create group and user
getent passwd mysql &> /dev/null  && echo "已有mysql用户，不再创建..."|| { groupadd mysql;useradd -u 3306 -r -g mysql -s /bin/false mysql; }



# then,find dependency
apt update 
if [ $? -eq 0 ];then
	apt install -y libaio-dev libncurses6 libtinfo6
else
	exit 1
fi

# create soft link for compatible
ln -s /lib/x86_64-linux-gnu/libncurses.so.6 /lib/x86_64-linux-gnu/libncurses.so.5
ln -s /lib/x86_64-linux-gnu/libtinfo.so.6 /lib/x86_64-linux-gnu/libtinfo.so.5

if [ -f $tar_local ];then
	echo "$tar_local 文件存在"
else
	echo "$tar_local 文件不存在，退出脚本."
	exit
fi

# uncompress source file
tar -xvf ${tar_local} -C ${install_path}

ln -sv "${install_path}${tar_dir_name}" "${install_path}mysql"

chown -R root:root "${install_path}mysql"


# config env PATH

echo "PATH=${install_path}mysql/bin:\$PATH" > /etc/profile.d/mysql.sh

source /etc/profile.d/mysql.sh


# prepare  data directory

[ -e ${data_path} ] || mkdir -pv "${data_path}"

chown -R mysql:mysql "${data_path}"


# prepare config file

cat > /etc/my.cnf <<EOF
[client]
socket=${data_path}mysql.sock
default-character-set=utf8mb4
[mysqld]
datadir=${data_path}
character-set-server=utf8mb4
socket=${data_path}mysql.sock

# Disabling symbolic-links is recommended to prevent assorted security risks

symbolic-links=0

# Settings user and group are ignored when systemd is used.

# If you need to run mysqld under a different user or group,

# customize your systemd unit file for mariadb according to the

# instructions in http://fedoraproject.org/wiki/Systemd
[mysqld_safe]

log-error=${data_path}mysql.log

pid-file=${data_path}mariadb.pid

EOF

# init database and set root password is empty
${install_path}mysql/scripts/mysql_install_db --user=mysql --datadir=${data_path}

# config service

\cp ${install_path}mysql/support-files/mysql.server /etc/init.d/mysqld

update-rc.d mysqld defaults
/usr/lib/systemd/systemd-sysv-install enable mysqld

systemctl start mysqld && echo "mysqld 启动成功!" || echo "mysqld 启动失败"

echo -e "#######\E[1;32m 已完成mariadb的安装和启动 \E[0m############"

echo -e  "初始密码为空，\E[1;31m必须修改初始密码！\E[0m
进入数据库命令:
source /etc/profile.d/mysql.sh
mysql -uroot 
修改初始密码sql语句如下:
alter user 'root'@'localhost' identified by '你的密码';
"





